﻿using Aliphant.UI.Browser.Managers;

using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;

namespace Aliphant.UI.Browser.Views
{
    /// <summary>
    /// BrowserTab.xaml 的交互逻辑
    /// </summary>
    public partial class BrowserTab : UserControl
    {
        public BrowserTab()
        {
            InitializeComponent();
            TabManager.Instance.UpdateInputUrlEvent += OnUpdateInput;
        }

        private void OnUpdateInput(string obj)
        {
            // TODO: 地址栏
            //input.Text = obj;
        }

        /// <summary>
        /// 鼠标中间单击关闭标签页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var border = sender as Border;
            var tab = border?.DataContext as WebView;
            if (tab != null)
            {
                if (e.MiddleButton == MouseButtonState.Pressed)
                {
                    tab.CloseCommand.Execute(null);
                }
            }
        }

        /// <summary>
        /// 地址栏回车跳转网页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            var txb = sender as TextBox;
            if (txb != null)
            {
                if (e.Key == Key.Enter)
                {
                    txb.Text = TabManager.FormatUrl(txb.Text);
                    TabManager.Instance.Create(txb.Text);
                }
            }
        }

        private void TabControl_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // 禁用Home、End、PageUp、PageDown键
            if (e.Key == Key.Home || e.Key == Key.End ||
                e.Key == Key.PageUp || e.Key == Key.PageDown)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StackPanel_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var panel = sender as StackPanel;
            if (panel != null && panel.Parent is ScrollViewer sv)
            {
                sv.ScrollToHorizontalOffset(sv.HorizontalOffset - e.Delta);
                e.Handled = true; // 阻止事件继续传递
            }
        }
    }
}
